package web.manager;

import bean.Manager;
import com.alibaba.fastjson.JSON;
import entity.ManagerEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "Connect", urlPatterns = "/dao/update/connect")
public class Connect extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonString = FANREN.getJson(request);
        System.out.println(jsonString);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");

        Manager manager = JSON.parseObject(jsonString, Manager.class);

        Query query = em.createNativeQuery("select mid from ManagerEntity where name = ? and pwd = ?");
        query.setParameter(1, manager.getName());
        query.setParameter(2, manager.getPwd());
        List list = query.getResultList();
        if (list.size() == 0) {
            throw new RuntimeException();
        } else {
            ManagerEntity managerEntity = em.find(ManagerEntity.class,list.get(0));
            Manager manager1 = (Manager) request.getSession().getAttribute("manager");
            managerEntity.setName(manager1.getName());
            managerEntity.setUsername(manager1.getUsername());
            em.persist(managerEntity);
        }
    }
}

